//
//  THAdjustTool.m
//  THImageEditDemo
//
//  Created by 希达 on 2018/3/27.
//  Copyright © 2018年 Tan.huang. All rights reserved.
//

#import "THAdjustTool.h"
#import "THBaseButton.h"
#import "GPUImageFramework.h"
#import "THFilterModel.h"

typedef enum : NSUInteger {
    THAdjustBrightness, // 亮度
    THAdjustContrast, // 对比度
    THAdjustLight, // 偏亮
    THAdjustDark, // 偏暗
    THAdjustTemperature, // 温度
    THAdjustTexture, // 锐化
} THAdjustType;


@interface THAdjustTool ()
/// 类型
@property (assign, nonatomic) THAdjustType type;
///
@property (weak, nonatomic) THBaseButton *autoBtn;
/// 分隔线
@property (weak, nonatomic) UIView *separateView;
/// 调整
@property (weak, nonatomic) UIScrollView *adjustScrollView;
/// 滑竿
@property (weak, nonatomic) UISlider *slider;

@property (weak, nonatomic) THBottomTool *bottomTool;

/// 当前选择类型
@property (copy, nonatomic) NSString *currentStr;

/// 滑竿值
@property (assign, nonatomic) CGFloat currentValue;
@property (nonatomic, assign) CGFloat originalValue;

@property (strong, nonatomic) UIImage *originalImage;
@property (strong, nonatomic) UIImage *thumbnailImage;


@end



@implementation THAdjustTool

- (void)dealloc {
    NSLog(@"%@释放了", NSStringFromClass(self.class));
}

- (void)configAdjustScrollView {

    CGFloat btnWidth = self.adjustScrollView.frame.size.height + 10;
    CGFloat left = 0;
    for (int i = 0; i < self.filterArray.count; i ++) {
        THFilterModel *model = self.filterArray[i];
        THBaseButton *adjustBtn = [THBaseButton buttonWithType:UIButtonTypeCustom];
        adjustBtn.type = 1;
        adjustBtn.tag = i + 1;
        adjustBtn.frame = CGRectMake(left * i + left + i * btnWidth, 5, btnWidth, btnWidth - 20);
        [adjustBtn addTarget:self action:@selector(adjustBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [adjustBtn setImage:[UIImage imageNamed:model.name] forState:UIControlStateNormal];
        [adjustBtn setTitle:model.name forState:UIControlStateNormal];
        [adjustBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        adjustBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.adjustScrollView addSubview:adjustBtn];
    }
    self.adjustScrollView.contentSize = CGSizeMake(btnWidth * self.filterArray.count, self.adjustScrollView.frame.size.height);
}

- (void)setup {
    [super setup];
    if (self.editor.filterArray) {
        self.filterArray = self.editor.filterArray;
    } else {
        self.filterArray = [NSMutableArray array];

        [self filterModelName:@"Brightness" min:-0.5 max:0.5 def:0];
        [self filterModelName:@"Contrast" min:0.5 max:4 def:1];
        [self filterModelName:@"Light" min:0 max:1 def:1];
        [self filterModelName:@"Dark" min:0 max:1 def:0];
        [self filterModelName:@"Temperature" min:4000 max:7000 def:5000];
        [self filterModelName:@"Texture" min:0 max:2 def:1];
    }

//    UIView *bgView = [[UIView alloc] initWithFrame:self.editor.bgView.bounds];
//    bgView.backgroundColor = [UIColor whiteColor];
//    [self.editor.bgView addSubview:bgView];
//    self.bgView = bgView;
//
//    [bgView addSubview:self.collectionView];

    _originalImage = [self.editor.imageView.image fixOrientation];
    _thumbnailImage = [UIImage imageWithCGImage:_originalImage.CGImage];


    CGFloat width = self.editor.bgView.frame.size.width;
    CGFloat btnWidth = (width - 50) / 4;

    THBaseButton *autoBtn = [THBaseButton buttonWithType:UIButtonTypeCustom];
    self.autoBtn = autoBtn;
    self.autoBtn.frame = CGRectMake(10, CGRectGetMaxY(self.collectionView.frame), btnWidth, btnWidth);
    self.autoBtn.type = 1;
    [self.autoBtn setImage:[UIImage imageNamed:@"fantasy"] forState:UIControlStateNormal];
    [self.autoBtn setImage:[UIImage imageNamed:@"fantasy_filled"] forState:UIControlStateSelected];
    [self.autoBtn setTitle:@"Auto" forState:UIControlStateNormal];
    [self.autoBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.bgView addSubview:self.autoBtn];
    /// 分隔线
     UIView *separateView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.autoBtn.frame), self.autoBtn.frame.origin.y + 10, 1, btnWidth - 20)];
    self.separateView = separateView;
    self.separateView.backgroundColor = [UIColor blackColor];
    [self.bgView addSubview:self.separateView];

    UIScrollView *adjustScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.separateView.frame), self.autoBtn.frame.origin.y, width - CGRectGetMaxX(self.separateView.frame), btnWidth)];
    self.adjustScrollView = adjustScrollView;
    [self configAdjustScrollView];
    [self.bgView addSubview:self.adjustScrollView];

    /// 滑竿
    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(self.adjustScrollView.frame.origin.x + 10, self.adjustScrollView.frame.origin.y, width - CGRectGetMaxX(self.separateView.frame) - 20, btnWidth)];
    self.slider = slider;
    self.slider.hidden = true;
    [self.slider addTarget:self action:@selector(sliderDidChange:) forControlEvents:UIControlEventValueChanged];
    self.slider.transform = CGAffineTransformMakeScale(0.5, 0.5);
    [self.bgView addSubview:self.slider];

    [self configBottomTool];

    [self affineTransformScale:nil toView:self.bgView isShow:YES];
}

- (void)cleanup {
    [self affineTransformScale:nil toView:self.bgView isShow:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgView removeFromSuperview];
        [self.workingView removeFromSuperview];
    });
}

// 底部按钮
- (void)configBottomTool {
    CGFloat heigth = 44 + (TZCommonTools.tz_isIPhoneX ? 34 : 0);
    CGFloat top = self.editor.bgView.height - heigth;
    THBottomTool *bottomTool = [[THBottomTool alloc] initWithFrame:CGRectMake(0, top, self.editor.bgView.width, heigth)];
    [self.bgView addSubview:bottomTool];
    self.bottomTool = bottomTool;

    @weakify(self);
    [bottomTool setDidBottomCancelBtnClickBlock:^{
        @strongify(self);

        [self.bottomTool hiddenDoneBtn];

        self.autoBtn.selected = NO;
        self.editor.titleName = @"Adjust";
        self.bottomTool.leftTitle = @"Back";
        self.editor.imageView.image = self.thumbnailImage;

        THFilterModel *model = self.filterArray[self.type];
        model.def = self.originalValue;
        [self.filterArray replaceObjectAtIndex:self.type withObject:model];

        [self affineTransformScale:self.adjustScrollView toView:self.slider isShow:NO];
    }];

    [bottomTool setDidBottomDoneBtnClickBlock:^{
        @strongify(self)
        self.editor.titleName = @"";
        self.editor.filterArray = self.filterArray;
        self.editor.picture = self.picture;
        [self.editor refreshTool];
    }];

    [bottomTool setDidBottomBackBtnClickBlock:^{
        @strongify(self)
        self.editor.titleName = @"";
        [self.editor refreshTool];
    }];
}


- (void)filterModelName:(NSString *)name min:(CGFloat)min max:(CGFloat)max def:(CGFloat)def {
    THFilterModel *model = [THFilterModel new];
    model.name = name;
    model.min = min;
    model.max = max;
    model.def = def;
    [self.filterArray addObject:model];
}

#pragma mark - Btn Click
- (void)adjustBtnClick:(UIButton *)sender {

    [self.bottomTool showDoneBtn];

    self.autoBtn.selected = true;
    self.slider.hidden = false;
    self.type = sender.tag - 1;

    self.currentStr = sender.titleLabel.text;
    self.bottomTool.leftTitle = @"Cancel";

    THFilterModel *model = self.filterArray[self.type];
    self.slider.maximumValue = model.max;
    self.slider.minimumValue = model.min;
    self.slider.value = model.def;
    self.editor.titleName = model.name;


    self.currentValue = model.def;
    self.originalValue = model.def;

    [self affineTransformScale:self.adjustScrollView toView:self.slider isShow:YES];
}

#pragma mark - UISlider Click
- (void)sliderDidChange:(UISlider *)slider {
    static BOOL inProgress = NO;
    
    if(inProgress){ return; }
    inProgress = YES;
    float value = slider.value;
    self.currentValue = value;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        /// 更新滑竿值
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < self.filterArray.count; i ++) {
            THFilterModel *model = self.filterArray[i];
            if ([model.name isEqualToString:self.currentStr]) {
                model.def = value;
                [self.filterArray replaceObjectAtIndex:i withObject:model];
            }
            [arr addObject:@(model.def)];
        }

        NSLog(@"%f --- %@", value, self.currentStr);

        UIImage *image = [self filterGroupWithImage:self.thumbnailImage brightness:[arr[0] floatValue] contrast:[arr[1] floatValue] highlights:[arr[2] floatValue] shadows:[arr[3] floatValue] temperature:[arr[4] floatValue] sharpness:[arr[5] floatValue]];
        [self.editor.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
        inProgress = NO;
    });
}

#pragma mark - 滤镜
- (UIImage *)filterGroupWithImage:(UIImage *)image brightness:(CGFloat)brightness contrast:(CGFloat)contrast  highlights:(CGFloat)highlights shadows:(CGFloat)shadows temperature:(CGFloat)temperature sharpness:(CGFloat)sharpness {
    if (!self.picture) {
        self.picture = [[GPUImagePicture alloc] initWithImage:image];
    }
    [self.picture removeAllTargets];
    GPUImageFilterGroup *filterGroup = [[GPUImageFilterGroup alloc] init];
    [self.picture addTarget:filterGroup];

    GPUImageBrightnessFilter *brightnessFilter = [[GPUImageBrightnessFilter alloc] init];
    brightnessFilter.brightness = brightness;

    GPUImageContrastFilter *contrastFilter = [[GPUImageContrastFilter alloc] init];
    contrastFilter.contrast = contrast;

    GPUImageHighlightShadowFilter *highlightShadowFilter = [[GPUImageHighlightShadowFilter alloc] init];
    highlightShadowFilter.highlights = highlights;
    highlightShadowFilter.shadows = shadows;

    GPUImageWhiteBalanceFilter *whiteBalanceFilter = [[GPUImageWhiteBalanceFilter alloc] init];
    whiteBalanceFilter.temperature = temperature;

    GPUImageUnsharpMaskFilter *sharpenFilter = [[GPUImageUnsharpMaskFilter alloc] init];
    sharpenFilter.intensity = sharpness;

    [brightnessFilter addTarget:contrastFilter];
    [contrastFilter addTarget:highlightShadowFilter];
    [highlightShadowFilter addTarget:whiteBalanceFilter];
    [whiteBalanceFilter addTarget:sharpenFilter];

    [filterGroup setInitialFilters:[NSArray arrayWithObject:brightnessFilter]];
    [filterGroup setTerminalFilter:sharpenFilter];


    // 处理图片
    [self.picture processImage];
    [filterGroup useNextFrameForImageCapture];

    return [filterGroup imageFromCurrentFramebuffer];
}








- (UIImage *)brightnessImage:(UIImage *)image value:(float)value {

//    if (!self.brightnessFilter) {
        GPUImageBrightnessFilter *brightnessFilter = [[GPUImageBrightnessFilter alloc] init];
//    }

    brightnessFilter.brightness = value;
    [brightnessFilter forceProcessingAtSize:image.size];
    [brightnessFilter useNextFrameForImageCapture];
//    if (!self.picture1) {
//        self.picture1 = [[GPUImagePicture alloc] initWithImage:image];
//    }
//    [self.picture1 addTarget:brightnessFilter];
//    [self.picture1 processImage];
    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:brightnessFilter];
    [picture processImage];
    return [brightnessFilter imageFromCurrentFramebuffer];
}

- (UIImage *)contrastImage:(UIImage *)image value:(float)value {

//    if (!self.contrastFilter) {
        GPUImageContrastFilter *contrastFilter = [[GPUImageContrastFilter alloc] init];
//    }
    contrastFilter.contrast = value;
    [contrastFilter forceProcessingAtSize:image.size];
    [contrastFilter useNextFrameForImageCapture];
//    if (!self.picture2) {
//        self.picture2 = [[GPUImagePicture alloc] initWithImage:image];
//    }
//    [self.picture2 addTarget:contrastFilter];
//    [self.picture2 processImage];
    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:contrastFilter];
    [picture processImage];
    return [contrastFilter imageFromCurrentFramebuffer];
}

- (UIImage *)lightImage:(UIImage *)image value:(float)value {
//    if (!self.highlightShadowFilter) {
        GPUImageHighlightShadowFilter *highlightShadowFilter = [[GPUImageHighlightShadowFilter alloc] init];
//    }
    highlightShadowFilter.highlights = value;
    [highlightShadowFilter forceProcessingAtSize:image.size];
    [highlightShadowFilter useNextFrameForImageCapture];
//    if (!self.picture3) {
//        self.picture3 = [[GPUImagePicture alloc] initWithImage:image];
//    }
//    [self.picture3 addTarget:highlightShadowFilter];
//    [self.picture3 processImage];
    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:highlightShadowFilter];
    [picture processImage];
    return [highlightShadowFilter imageFromCurrentFramebuffer];
}

- (UIImage *)darkImage:(UIImage *)image value:(float)value {
//    if (!self.highlightShadowFilter) {
        GPUImageHighlightShadowFilter *highlightShadowFilter = [[GPUImageHighlightShadowFilter alloc] init];
//    }
    highlightShadowFilter.shadows = value;
    [highlightShadowFilter forceProcessingAtSize:image.size];
    [highlightShadowFilter useNextFrameForImageCapture];
//    if (!self.picture4) {
//        self.picture4 = [[GPUImagePicture alloc] initWithImage:image];
//    }
//    [self.picture4 addTarget:highlightShadowFilter];
//    [self.picture4 processImage];

    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:highlightShadowFilter];
    [picture processImage];
    return [highlightShadowFilter imageFromCurrentFramebuffer];
}

- (UIImage *)temperatureImage:(UIImage *)image value:(float)value {

//    if (!self.whiteBalanceFilter) {
        GPUImageWhiteBalanceFilter *whiteBalanceFilter = [[GPUImageWhiteBalanceFilter alloc] init];
//    }
    whiteBalanceFilter.temperature = value;
    [whiteBalanceFilter forceProcessingAtSize:image.size];
    [whiteBalanceFilter useNextFrameForImageCapture];
//    if (!self.picture5) {
//        self.picture5 = [[GPUImagePicture alloc] initWithImage:image];
//    }
//    [self.picture5 addTarget:whiteBalanceFilter];
//    [self.picture5 processImage];

    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    [picture addTarget:whiteBalanceFilter];
    [picture processImage];
    return [whiteBalanceFilter imageFromCurrentFramebuffer];
}

- (UIImage *)textureImage:(UIImage *)image value:(float)value {

//    if (!self.sketchFilter) {
        GPUImageSketchFilter *sketchFilter = [[GPUImageSketchFilter alloc] init];
//    }

    GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:image];
    sketchFilter.edgeStrength = value;
    [sketchFilter forceProcessingAtSize:image.size];
//    if (!self.picture) {
        [picture addTarget:sketchFilter];
//    }
    [picture processImage];
    [sketchFilter useNextFrameForImageCapture];
    return [sketchFilter imageFromCurrentFramebuffer];
}



@end










